package com.fruit.controller.wap.pay;


import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.fruit.controller.base.BaseController;
import com.fruit.pojo.pay.PayInfo;
import com.fruit.resolver.DefiniteException;
import com.fruit.service.pay.PayHandel;
import com.fruit.util.CommonUtil;
import com.fruit.util.ResultInfo;

import lombok.extern.slf4j.Slf4j;


@Slf4j
@Controller("wapPayController")
@RequestMapping(value = "/wap/pay")
public class PayController extends BaseController {

	
	@Autowired
	private PayHandel payHandelService;
	
	@Value("${h5_domain}")
	private String h5Domain;
	
	@Value("${domain}")
	private String domain;

	@RequestMapping(value = "submitOrder", method = { RequestMethod.POST,RequestMethod.GET })
	public ModelAndView submitOrder (PayInfo pi, HttpServletResponse response, HttpServletRequest request,HttpSession session) {
		String tradeId = CommonUtil.getUUID();
		Integer userId = (Integer) session.getAttribute("userId");	
		pi.setUserId(userId);
		log.info("[{}]-【订单提交】-【用户：{}】-【开始】",tradeId,pi.getUserId());
			ModelAndView view = this.getModelAndView();
			log.info("[{}]-【订单提交】-【调用保存订单服务】",tradeId);
			Map<String, Object> resMap = payHandelService.saveSubmitOrder(tradeId, pi);
			ResultInfo ri = (ResultInfo)resMap.get("result");
			if(ResultInfo.ERROR.equals(ri.getState()) ){
				if(ri.getCode().equals("user_not_real")){
					log.info("[{}]-【订单提交】-【用户未认证】",tradeId);	
					view.setViewName("redirect:"+h5Domain+"/legalize?returnUrl="+domain+"/wap/goods/detail?id="+pi.getGoodsTimeId());
				}else{
					log.error("[{}]-【订单提交】-【异常】-【{}：{}】",tradeId,ri.getCode(),ri.getMessage());
					throw new DefiniteException(ri.getMessage());
				}
			}else{
				log.info("[{}]-【订单提交】-【成功】",tradeId);	
				String transactionCode = (String)resMap.get("transactionCode");
				view.setViewName("redirect:/wap/lightpay/lightPayCashier?transactionCode="+transactionCode);
			}
			
		log.info("[{}]-【订单提交】-【结束】",tradeId);	
		return view;
	}
	
}
